using LangChainServer.Models;
using LangChainServer.Services;
using Microsoft.AspNetCore.Mvc;

namespace LangChainServer.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ChatController : ControllerBase
    {
        private readonly IChatService _chatService;
        private readonly ILogger<ChatController> _logger;

        public ChatController(IChatService chatService, ILogger<ChatController> logger)
        {
            _chatService = chatService;
            _logger = logger;
        }

        [HttpPost]
        /// <summary>
        /// 直连 OpenAI 兼容接口的统一聊天入口（HTTP 代理）。
        /// </summary>
        /// <param name="request">通用聊天请求（模型、温度、消息列表等）。</param>
        /// <param name="ct">取消标记。</param>
        /// <returns>返回模型的聊天回复。</returns>
        public async Task<ActionResult<ChatResponse>> Post([FromBody] ChatRequest request, CancellationToken ct)
        {
            try
            {
                var result = await _chatService.ChatAsync(request, ct);
                return Ok(result);
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogWarning(ex, "Chat configuration error");
                return BadRequest(new { error = ex.Message });
            }
        }
    }
}
